package cn.fastoo.service;

import cn.fastoo.common.dao.*;
import cn.fastoo.common.entity.*;
import cn.fastoo.common.sampleframe.dto.JsonResult;
import cn.fastoo.common.sampleframe.search.Search;
import cn.fastoo.common.utils.BigDecimalUtil;
import cn.fastoo.common.utils.ChargeUtil;
import cn.fastoo.common.utils.Constant;
import cn.fastoo.common.utils.MessageHelper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

/**
 * Created by lowkey on 17/7/24.
 */
@Component
@Transactional
public class UserService {

    private final static Logger logger = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserBaseDao userBaseDao;
    @Autowired
    private SmsrecordDao smsrecordDao;
    @Autowired
    private UserAccountDao userAccountDao;
    @Autowired
    private UserBalanceRemindDao userBalanceRemindDao;
    @Autowired
    private FastooMtDetailDao fastooMtDetailDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public JsonResult saveNewUserBase(String loginName, String password){
        UserBase userBase = userBaseDao.findOne(new Search().addSearchFilter("EQ_loginName",loginName));
        if(userBase !=null){
            return new JsonResult(101,"用户名已存在");
        }
        userBase = new UserBase();
        userBase.setLoginName(loginName);
        userBase.setPassword( DigestUtils.sha256Hex(password));
        userBase.setStatus(Constant.UserStatus.Normal.getValue());
        userBase.setBalance(5D);
        userBaseDao.insert(userBase);
        //生成account?
        UserAccount userAccount = new UserAccount();
        userAccount.setUserBaseId(userBase.getId());
        userAccount.setApiKey(UUID.randomUUID().toString().replace("-",""));
        userAccountDao.insert(userAccount);

        return new JsonResult(0,"注册成功");
    }


    public JsonResult changePwd(String loginName,String password){
        UserBase userBase = userBaseDao.findOne(new Search().addSearchFilter("EQ_loginName",loginName));
        if(userBase==null){
            return new JsonResult(102,"没有此用户");
        }
        userBase.setPassword(DigestUtils.sha256Hex(password));
        userBaseDao.update(userBase);
        return new JsonResult(0,"保存成功");
    }

    public String setUserBalanceRemind(Double remindBalance, String startTime, String endTime, Long userBaseId) {
        UserBalanceRemind remind = userBalanceRemindDao.findOne(new Search().addSearchFilter("EQ_userBaseId",userBaseId));

        if (remind != null) {
            remind.setRemindBalance(remindBalance);
            remind.setRemindRangeTime(startTime + "-" + endTime);
            userBalanceRemindDao.update(remind);
        } else {
            remind = new UserBalanceRemind();
            remind.setUserBaseId(userBaseId);
            remind.setRemindBalance(remindBalance);
            remind.setRemindRangeTime(startTime+"-"+endTime);
            userBalanceRemindDao.insert(remind);
        }
        return JsonResult.create(0,"保存成功");
    }

    public String delSignature(String apiKey) {
        UserAccount userAccount = userAccountDao.findOne(new Search().addSearchFilter("EQ_apiKey",apiKey));
        if (userAccount!=null) {
            userAccount.setSignName("");
            userAccount.setSignApplyTime(null);
            userAccount.setSignAuditTime(null);
            userAccountDao.update(userAccount);
        }
        return JsonResult.create(0,"删除成功");
    }

    public void updateSmsrecordStatus(String da, String localMsgid, String result) {
        if (StringUtils.isBlank(result)) {
            return;
        }

        Smsrecord smsrecord = smsrecordDao.findOne(new Search().addSearchFilter("EQ_localMsgid",localMsgid).addSearchFilter("EQ_destAddr",da));
        if (smsrecord != null) {
            JSONObject resultObject = JSON.parseObject(result);
            if (resultObject.getInteger("code")==0) {
                JSONObject json = (JSONObject) resultObject.get("data");
                String msgid = json.getString("msgid");
                smsrecord.setFastooMsgid(msgid);
                smsrecord.setMtStatus(Constant.MtStatus.Success.getValue());
            } else {
                smsrecord.setMtStatus(Constant.MtStatus.Fail.getValue());
            }
            smsrecord.setMtStatuscode(resultObject.getString("code"));
            smsrecord.setMtErrorcode(resultObject.getString("msg"));
            smsrecord.setSendTime(new Date());
            smsrecordDao.update(smsrecord);

        } else {
            logger.info("没找到对应Smsrecord记录:localMsgid="+localMsgid+",da="+da);
        }
    }

    public void updateAndCharge(String da, String fastooMsgid, String errcode, String channelMsgid) {
        FastooMtDetail mtDetail = fastooMtDetailDao.findOne(new Search().addSearchFilter("EQ_fastooMsgid",fastooMsgid).addSearchFilter("EQ_destAddr",da));
        String errorText = MessageHelper.getErrorStr(errcode);
        if ("000".equals(errcode)) {
            mtDetail.setSantoChannelMsgid(channelMsgid);
            mtDetail.setMtStatus(Constant.MtStatus.Success.getValue());
            mtDetail.setMtStatuscode(errcode);
        } else {
            mtDetail.setMtStatus(Constant.MtStatus.Fail.getValue());
            mtDetail.setMtStatuscode(errcode);
        }
        mtDetail.setMtErrorcode(errorText);
        mtDetail.setSendTime(new Date());
        fastooMtDetailDao.update(mtDetail);

        if (mtDetail.getMtStatus()==1) {
            //扣费
            charge(mtDetail,mtDetail.getApiKey());

            //扣费记录
        }
    }




    private void charge(FastooMtDetail mtDetail,String apiKey) {
        Double price = mtDetail.getPrice();
        Integer feeCount = mtDetail.getFeeCount();
        Double cost = BigDecimalUtil.mul(price,feeCount);
        ChargeUtil.charge(jdbcTemplate,cost,apiKey,mtDetail.getDestAddr());
    }
}
